<?php

namespace App\Http\Controllers\Api;

use App\Models\Site;
use App\Models\Icp;
use QL\QueryList;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;

class IcpController extends Controller
{
    //
    public function data($id, $array)
    {
        $flight = Icp::updateOrCreate(
            ['site_id' => $id],
            [
                'site_id'       => $id,
                'name'          => $array['name'],
                'type'          => $array['type'],
                'now_icp'       => $array['now_icp'],
                'check_date'    => $array['check_date'] ? $array['check_date'] : date('Y-m-d', time()),
            ]
        );
        $this->ziyuan($id);
        return response()->json(['msg' => '数据已经获取成功!3秒后,刷新页面', 'code' => '0'],200);
    }
    
    public function search($id)
    {
        $site    = Site::where('id',$id)->first();
        $chinaz    = $this->chinaz($site->url);
        if($chinaz) {
            return $this->data($id, $chinaz);
        }
        $aizhan    = $this->aizhan($site->url);
        if($aizhan) {
            return $this->data($id, $aizhan);
        }
        return response()->json(['msg' => '您需要的数据!出现问题,正在修理过程中……请稍候重试!……', 'code' => '1'],200);
    }
    public function aizhan($name)
    {
        $aizhan = $this->check('https://icp.aizhan.com/'.$name);
        if(!$aizhan) {
            return false;
        }
        $ql = QueryList::html($aizhan)->rules([
            //采集规则
            'name'          => ['tr:eq(0)>td:eq(1)','text'],
            'type'          => ['tr:eq(1)>td:eq(1)','text'],
            'now_icp'       => ['tr:eq(2)>td:eq(1)','text'],
            'check_date'    => ['tr:eq(6)>td:eq(1)','text'],
        ])->range('#icp-table')->query()->getData(function ($item) use ($aizhan) {
            if($item['type'] == '个人'){
                $content = QueryList::html($aizhan)->rules([
                    'check_date'    => ['tr:eq(7)>td:eq(1)','text'],
                ])->range('#icp-table')->query()->getData()->all();
                $item['check_date']  = $content[0]['check_date'];
            }
            return $item;
        });
        $data   = $ql->all();
        if(array_key_exists(0,$data)){
            return [
                'name'      => $data[0]['name'],
                'type'      => $data[0]['type'],
                'now_icp'   => $data[0]['now_icp'],
                'check_date'=> $data[0]['check_date'],
            ];
        }else{
            return false;
        }
    }
    public function chinaz($name)
    {
        $chinaz = $this->check('http://icp.chinaz.com/'.$name);
        if(!$chinaz) {
            return false;
        }
        $ql = QueryList::html($chinaz)->rules([
            //采集规则
            'name'          => ['li:eq(0)>p','text'],
            'type'          => ['li:eq(1)>p','text'],
            'now_icp'       => ['li:eq(2)>p','text'],
            'check_date'    => ['li:eq(7)>p','text'],
        ])->range('#first')->query()->getData();
        $data   = $ql->all();
        if(array_key_exists(0,$data)){
            return [
                'name'       => str_replace('使用高级查询纠正信息','',$data[0]['name']),
                'type'       => $data[0]['type'],
                'now_icp'    => str_replace('查看截图','',$data[0]['now_icp']),
                'check_date' => $data[0]['check_date'],
            ];
        }else{
            return false;
        }
    }
    //抓取网址
    function check($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);//抓取网址
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Baiduspider/3.0; +http://www.baidu.com/search/spider.html)");//伪造百度蜘蛛头部
        $ip = '220.181.7.121';
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:' . $ip, 'CLIENT-IP:' . $ip));//伪造百度蜘蛛IP
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//
//        curl_setopt($ch, CURLOPT_HEADER, true); //抓取服务器信息
        curl_setopt($ch, CURLOPT_NOBODY, false); //抓取网页信息
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //支持301跳转
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 30); //网页等待时间
        $data = curl_exec($ch);
        $code = curl_getinfo($ch);
        curl_close($ch);
        if($code['http_code'] == 200){
            return $data;
//            $parse_url  = parse_url($code['url']);
//            return      $parse_url['scheme'].'://'.$parse_url['host'];
        }else{
            return false;
        }
    }
    
    function ziyuan($id)
    {
        $urls = array(
            env('APP_URL').'/siteinfo-'.$id.'.html',
        );
        $api = env('BAIDUZHANZHANG');
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        return $result;
    }
}